/*
https://leetcode-cn.com/problems/concatenated-words/solution/lian-jie-ci-by-leetcode-solution-mj4d/
 */
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class Solution472 {

    Trie trie=new Trie();

    static class Trie {
        Trie[] children;
        boolean isEnd;

        public Trie() {
            children = new Trie[26];
            isEnd = false;
        }
    }

    public List<String> findAllConcatenatedWordsInADict(String[] words) {
        Arrays.sort(words, Comparator.comparingInt(String::length));
        List<String> ans=new ArrayList<>();
        for (String word : words) {
            if (word.length()==0){
                continue;
            }
            if (dfs(word,0)){
                ans.add(word);
            }else{
                insert(word);
            }
        }
        return ans;
    }

    public void insert(String word){
        Trie node = trie;
        for (int i = 0; i < word.length(); i++) {
            char ch = word.charAt(i);
            int index = ch - 'a';
            if (node.children[index] == null) {
                node.children[index] = new Trie();
            }
            node = node.children[index];
        }
        node.isEnd = true;
    }

    public boolean dfs(String word,int start){
        if (start==word.length()){
            return true;
        }
        Trie node=trie;
        for (int i=start;i<word.length();i++){
            node=node.children[word.charAt(i)-'a'];
            if (node==null){
                return false;
            }
            if (node.isEnd){
                if (dfs(word,i+1)){
                    return true;
                }
            }
        }
        return false;
    }

    public static void main(String[] args) {
        System.out.println(new Solution472().findAllConcatenatedWordsInADict(new String[]{"cat","cats","catsdogcats","dog","dogcatsdog","hippopotamuses","rat","ratcatdogcat"}));
    }
}
